from pathlib import Path

import pygame
from openai import OpenAI

from day18.set_env import read_yaml


def play_mp3(file):
    # 初始化一个 Pygame 的混音器
    pygame.mixer.init()
    # 填入要加载的 MP3 音频文件的路径
    pygame.mixer.music.load(file)
    # 开始播放加载的音频文件
    pygame.mixer.music.play()
    # 循环检查音频是否在播放
    while pygame.mixer.music.get_busy():
        # 创建一个时钟对象，并设置每秒最多调用 tick 方法 10 次，这是为了降低 CPU 的负载，因为不需要每毫秒检查音频是否完成播放
        pygame.time.Clock().tick(10)


def test_with_openai():
    dic = read_yaml("conf.yaml")
    # 初始化OpenAI对象
    client = OpenAI(base_url=dic.get("OPENAI_BASE_URL"), api_key=dic.get("OPENAI_API_KEY"))

    # 实例化出来一个音频创建对象
    response = client.audio.speech.create(
        model='tts-1',
        voice='alloy',
        input="Mama always said life was like a box of chocolates. You never know what you're gonna get."
    )
    # 给出音频输出路径
    speech_file_path = Path(__file__).parent / "speech.mp3"
    # 使用流式传输实时音频
    response.stream_to_file(speech_file_path)
    play_mp3(speech_file_path)
